/**
 * Copyright (c) 快宝网络 kuaidihelp.com Co., Ltd. All Rights Reserved 禁止外泄以及用于其它的商业用途
 */

import React, { useEffect, useState } from 'react';
import PageHeaderLayout from '@/layouts/PageHeaderLayout';
import { Button, Col, Form, Row, message, Checkbox, Modal } from 'antd';
import { useDispatch, useSelector } from 'dva';
import ChooseSub from '@/components/_pages/Order/ExportOrder/ChooseSub';
import ChooseDate from '@/components/_pages/Order/ExportOrder/ChooseDate';
import TimeType from '@/components/_pages/Order/ExportOrder/TimeType';
import ChooseFields from '@/components/_pages/Order/ExportOrder/Fields';
import { addTask } from '@/services/order';
import { useDebounceFn } from 'ahooks';
import moment from 'moment/moment';
import styles from './index.less';

const FormItem = Form.Item;

const formItemLayout = {
  labelCol: {
    sm: { span: 2 },
  },
  wrapperCol: {
    sm: { span: 22 },
  },
};

const startDate = moment()
  .startOf('day')
  .subtract(6, 'days');
const endDate = moment()
  .startOf('day')
  .subtract(0, 'days');

const ExportOrder = props => {
  const { form } = props;
  const { getFieldDecorator, validateFields } = form;

  const [submitting, setSubmitting] = useState(false);
  const dispatch = useDispatch();

  const { content = [], innList = [], courierList = [] } = useSelector(
    ({ order }) => order.exportOrderConfig,
  );

  useEffect(() => {
    dispatch({
      type: 'order/getExportOrderConfig',
    });
  }, []);

  const { run: handleSubmit } = useDebounceFn(
    () => {
      setSubmitting(true);
      validateFields((err, values) => {
        if (err) {
          setSubmitting(false);
          return;
        }
        const {
          userType: { type: userType, ids },
          isLogistics,
          dateType,
          exportInfo,
        } = values;
        const params = {
          userType,
          exportInfo,
          isLogistics: isLogistics ? 1 : '',
          dateType,
        };
        if (values.date) {
          values.date = values.date.map(d => moment(d).format('YYYY-MM-DD'));
          const [start, end] = values.date;
          params.starTime = start;
          params.endTime = end;
        }

        if (userType == 'inn') {
          params.user_id = (ids.includes('all') ? innList : ids).map(v => v.inn_id || v).join(',');
        } else {
          params.user_id = (ids.includes('all') ? courierList : ids)
            .map(v => v.kdy_id || v)
            .join(',');
        }

        addTask(params)
          .then(res => {
            if (res.code == 0) {
              Modal.info({
                title: '温馨提示',
                content: '导出数据申请已提交，请至【报表下载】处下载',
              });
            } else {
              message.error(res.msg);
            }
            setSubmitting(false);
          })
          .catch(() => {
            setSubmitting(false);
          });
      });
    },
    {
      wait: 300,
      leading: true,
      trailing: false,
    },
  );

  const timeRangeValidator = (rule, value, callback) => {
    const [start] = value || [];
    const toDay = moment().format('YYYY-MM-DD');

    // 设置日期区间，最大不超过31天
    const section = moment(toDay).diff(moment(start), 'month');
    if (section > 6) {
      return callback('只可选择近6个月的数据');
    }
    return callback();
  };

  return (
    <PageHeaderLayout title="导出对账单">
      <div className={styles.main}>
        <Form {...formItemLayout}>
          <FormItem label="选择下属">
            {getFieldDecorator('userType', {
              initialValue: {
                type: 'inn',
                ids: ['all'],
              },
            })(<ChooseSub />)}
          </FormItem>
          <FormItem label="时间类型">
            {getFieldDecorator('dateType', {
              initialValue: 'orderCreation',
            })(<TimeType />)}
          </FormItem>
          <FormItem label="选择时间">
            {getFieldDecorator('date', {
              initialValue: [startDate, endDate],
              rules: [{ validator: timeRangeValidator }],
            })(<ChooseDate />)}
          </FormItem>
          <FormItem label="其他设定">
            {getFieldDecorator('isLogistics', {
              valuePropName: 'checked',
            })(<Checkbox>过滤无物流信息的数据</Checkbox>)}
          </FormItem>
          <FormItem>
            {getFieldDecorator('exportInfo', { initialValue: content })(<ChooseFields />)}
          </FormItem>
        </Form>
        <Row type="flex" justify="center">
          <Col>
            <Button loading={submitting} type="primary" onClick={handleSubmit}>
              生成对账单
            </Button>
          </Col>
        </Row>
      </div>
    </PageHeaderLayout>
  );
};

export default Form.create()(ExportOrder);
